define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                table.render({
                    elem: '#table'
                    ,url:'kuerp/accounts_receivable/index'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows, //解析数据列表
                            "all_balance": res.all_balance,
                            "all_receivable": res.all_receivable,
                            "all_advance": res.all_advance,
                        };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,defaultToolbar: [
                        {name:'filter', title: __('Filter')}, // 列筛选
                         {
                            name: 'exports',
                            title: __('Exports'),
                            onClick: function(obj) {
                              // 获得数据并清除临时字段
                              var data = table.clearCacheKey(obj.data);
                              // 当前示例配置项
                              var options = obj.config;

                              if(data.length > 0 || Object.keys(data).length > 0){
                                table.exportFile(options.id, null, 'csv');
                              }else{
                                layer.msg(__('No data'));
                              }
                             
                            }
                          },
                        {name:'print', title: __('Print')} // 打印
                    ]
                    ,totalRow: true
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,where: {
                        filter:JSON.stringify(getSearch()),
                        op:JSON.stringify(getOp()),
                    }
                    ,cols: [[
                        {checkbox: true},
                        {field: 'customer_name', title: __('Customers.customer_name')},
                        {field: 'purchase_time', title: __('Purchase_time'),width: 130},
                        {field: 'purchase_code', title: __('Purchase_code'),width: 150,'totalRow':__('Total')},
                        {field: 'business_type', title: __('Business_type'),templet: function (d) {
                                if(d.business_type==1){
                                    return __('Business_type 1');
                                }else if(d.business_type==2){
                                    return __('Business_type 2');
                                }else if(d.business_type==3){
                                    return __('Business_type 3');
                                }else if(d.business_type==4){
                                    return __('Business_type 4');
                                }else if(d.business_type==5){
                                    return __('Business_type 5');
                                }else if(d.business_type==6){
                                    return __('Business_type 6');
                                }else if(d.business_type==7){
                                    return __('Business_type 7');
                                }else if(d.business_type==8){
                                    return __('Business_type 8');
                                }else{
                                    return '';
                                }
                            }},
                        {field: 'receivable', title: __('Receivable'),totalRow:true},
                        {field: 'advance', title: __('Advance'),totalRow:true},
                        {field: 'balance', title: __('Balance'),totalRow:true},
                        {field: 'staff_member', title: __('Staff_member_id')},
                        {field: 'remark', title: __('Remark')},
                    ]],
                    done: function(res, curr, count){
                        if (res.count == 0 && !searchStatus) {
                            var html = '<div class="layui-none no-results"><span>' + __('Please enter search criteria and click search') + '</span></div>';
                            $(".layui-table-main").html(html);
                        }else{
                            var obj = this.elem.next();
                            obj.find('.layui-table-total td[data-field="receivable"] .layui-table-cell').text(res.all_receivable);
                            obj.find('.layui-table-total td[data-field="advance"] .layui-table-cell').text(res.all_advance);
                            obj.find('.layui-table-total td[data-field="balance"] .layui-table-cell').text(res.all_balance);
                        }
                    }
                });

                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                    }
                });
                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                    });
                });
                var searchStatus = false;
                function getSearch() {
                    var search = {};
                    var purchase_time = $('#purchase_time').val();
                    if(purchase_time!=''){
                        search.purchase_time = purchase_time;
                    }
                    var customers_id = $('#customers_id').val();
                    if(customers_id!=''){
                        search.customers_id = customers_id;
                    }
                    var staff_member_id = $('#staff_member_id').val();
                    if(staff_member_id!=''){
                        search.staff_member_id = staff_member_id;
                    }
                    if(purchase_time=='' && customers_id=='' && staff_member_id==''){
                        searchStatus = false;
                        search.id = 1;
                    }else{
                        searchStatus = true;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.purchase_time = 'RANGE';
                    op.id = '<';
                    return op;
                }
            });
            Controller.api.bindevent();
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {

                layui.use(['table','form'], function(){
                    var supplyer_div = xmSelect.render({
                        el: '#customers_ids',
                        filterable: true,
                        paging: true,
                        tips: __('Please select customer'),
                        language: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        pageSize: 5,
                        // remoteSearch: true,
                        pageRemote: true,
                        remoteMethod: function (val, cb, show, pageIndex) {
                            $.ajax({
                                url: "kuerp/customers/index",
                                type: 'GET',
                                crossOrigin: true,
                                dataType: 'json',
                                cache: false,
                                async: true,
                                data: {
                                    keywords: val,
                                    filter:JSON.stringify({"customer_name":val}),
                                    op:JSON.stringify({"customer_name":'like'}),
                                    page: pageIndex,
                                    limit: 5
                                },
                                success: function (data) {
                                    var TotalCount = data.total;
                                    var Pages = Math.ceil(TotalCount/5);
                                    var list = [];
                                    $(data.rows).each(function (k,v) {
                                        var row = [];
                                        row['name'] = v.customer_name;
                                        row['value'] = v.id;
                                        list.push(row)
                                    });
                                    setTimeout(function () {
                                        cb(list, Pages)
                                    }, 100)
                                },
                                error: function (data) {
                                    cb([], 0);
                                }
                            });
                        },
                        on: function(data){
                            var arr = data.arr;
                            var change = data.change;
                            var isAdd = data.isAdd;
                            if(!isAdd){
                                $('#customers_id').val('');
                            }
                            if(change.length>0){
                                for (let i in arr){
                                    if(change[0].parentId==arr[i].parentId){
                                        arr.splice(i,1,change[0]);
                                    }
                                }
                            }
                            if(arr.length>0){
                                if(arr[0]['value']!=undefined){
                                    $('#customers_id').val(arr[0]['value']);
                                }
                            }
                            return Array.from(new Set(arr));
                        },
                    });

                    var kuerp_customers = Config.kuerp_customers;
                    if(kuerp_customers!=undefined){
                        var newArr = [];
                        newArr.push({name: kuerp_customers.customer_name, value: kuerp_customers.id,});
                        supplyer_div.setValue(newArr);
                    }

                    var set = Config.set;
                    var examine = parseInt(set.examine.is_checked);
                    if(isNaN(examine)){
                        examine = 0;
                    }
                    if(examine==1 && Config.examine_status==1){
                        supplyer_div.update({disabled:true})
                    }
                });

                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    laydate.render({
                         lang: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        elem: '#purchase_time',
                        type: 'datetime',
                        range: true
                    });
                });
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    parent.location.reload();
                });
            }
        }
    };
    return Controller;
});